//
//  SelectPersonViewController.m
//  Marketing
//
//  Created by Hanen 3G 01 on 16/5/17.
//  Copyright © 2016年 Hanen 3G 01. All rights reserved.
//

#import "SelectPersonViewController.h"
#import "HeaderView.h"
#import "ChooseDepartCell.h"
#import "HeaderView2.h"
#define KISExpand @"ISExpand"

#define CellH 55.0f
@interface SelectPersonViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,HeaderViewDelegate,HeaderView2Delegate>
{
    UIView *dimmingView;
    UIView *_backView;
    
    NSMutableArray  *_departArray;
    NSMutableArray  *_departManArray;
    NSMutableArray  *_expandArray;
    NSMutableArray  *_selectedNameArray;
    NSMutableArray  *_selectedModelAray;
    UIView *vi2;
    BOOL  currentSelected;
    HeaderView2  *_headerVie2;
    BOOL isAllSelected;
    NSInteger  departMentCount;
    
    HeaderView2 *hview2;

}
@property (nonatomic,strong) UIView *alphaView;
@end

@implementation SelectPersonViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.view.backgroundColor = [UIColor clearColor];
    
    
    _departArray = [NSMutableArray array];
    _departManArray = [NSMutableArray array];
    _expandArray = [NSMutableArray array];
    _selectedNameArray = [NSMutableArray array];
    _selectedModelAray = [NSMutableArray array];
    _searchArray = [NSMutableArray array];
    
    currentSelected = NO;
    _alphaView = [[UIView alloc] initWithFrame:CGRectMake(50, 0, self.view.width-50, self.view.height)];
    UIView *baseView = [[UIView alloc] initWithFrame:self.view.frame];
    _alphaView.backgroundColor = [UIColor clearColor];
    
    baseView.backgroundColor = [UIColor blackColor];
    baseView.alpha = 0.2;
    UIButton *backViewBtn = [[UIButton alloc] initWithFrame:baseView.frame];
    backViewBtn.backgroundColor = [UIColor clearColor];
    [backViewBtn addTarget:self action:@selector(closeSelectView) forControlEvents:UIControlEventTouchUpInside];
    [baseView addSubview:backViewBtn];
    [self.view addSubview:baseView];
    [self.view addSubview:_alphaView];
    
    
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KSCreenW, KSCreenH)];
    image.image =self.screenShot;
    [self.view insertSubview:image atIndex:0];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    self.view.frame=CGRectMake(0,20,KSCreenW,KSCreenH-20);
    //    self.view.bounds.origin.y = 20;
    UIView *navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 20, _alphaView.width, 44)];
    navBar.backgroundColor = NavBackColor;
//    navBar.backgroundColor = UIColorFromRGB(0xf2f2f2);
    [_alphaView addSubview:navBar];
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 30 , 12.0, 19.0)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"HY_Btn_arrow"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"HY_Btn_arrow"] forState:UIControlStateHighlighted];
    [backBtn addTarget:self action:@selector(closeSelectView) forControlEvents:UIControlEventTouchUpInside];
    [_alphaView addSubview:backBtn];
    
    UILabel *titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(40,30, _alphaView.width-80, 30)];
    titleLbl.text = @"人员";
    titleLbl.font = [UIFont systemFontOfSize:17.0f];
    titleLbl.textColor = [UIColor whiteColor];
    titleLbl.textAlignment = NSTextAlignmentCenter;
    [_alphaView addSubview:titleLbl];
    
    [_alphaView addSubview:[ViewTool getLineViewWith:CGRectMake(0,63, _alphaView.width, 1) withBackgroudColor:grayListColor]];
    
    UIButton *resetBtn = [[UIButton alloc] initWithFrame:CGRectMake(_alphaView.width- 30, backBtn.y,20.0, 20.0)];
    [resetBtn setBackgroundImage:[UIImage imageNamed:@"HY_nav_icon_refresh"] forState:UIControlStateNormal];
    [resetBtn setBackgroundImage:[UIImage imageNamed:@"HY_nav_icon_refresh"] forState:UIControlStateHighlighted];
    [resetBtn addTarget:self action:@selector(resetView:) forControlEvents:UIControlEventTouchUpInside];
    [_alphaView addSubview:resetBtn];
    
         [self addSearchBar];
    [self addAllUsers];
//    [self initData];
    
    self.isAll = NO;
 
    _departs = [NSMutableArray array];
    _selectedDeparts = [NSMutableArray array];
    _selectedUsers = [NSMutableArray array];
    _users = [NSMutableArray array];
    _allUsers = [NSMutableArray array];
    _selectedArray = [NSMutableArray array];
    
    [self addSureBtn];
//    [self addAllUsers];//所有的数据
//    [self addSearchBar];
}

- (void)addSureBtn
{
    CGFloat space = [UIView getWidth:8.0];
    UIView *postView = [ViewTool getLineViewWith:CGRectMake(_alphaView.x, _alphaView.height - TabbarH, _alphaView.width, TabbarH) withBackgroudColor:[UIColor whiteColor]];
    [self.view addSubview:postView];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(1.5 * space, 0.6 * space, postView.width - 3 * space, postView.height - 1.2 * space)];
    btn.layer.cornerRadius = 4.0f;
    btn.layer.masksToBounds = YES;
    btn.layer.shouldRasterize = YES;
    
    [btn addTarget:self action:@selector(selectStaff) forControlEvents:UIControlEventTouchUpInside];
//    btn.backgroundColor = redBackColor;
    [btn setBackgroundImage:[UIImage imageNamed:@"HY_btn_red_normal.png"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"HY_btn_red_press.png"] forState:UIControlStateSelected];
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [postView addSubview:btn];
    
    UIView *line3 = [ViewTool getLineViewWith:CGRectMake(0, 0, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [postView addSubview:line3];
    

}
- (void)selectStaff
{
    NSLog(@"选择的人的个数 四 几个%ld，%ld",_selectedModelAray.count,_selectedNameArray.count);
    
    for (UserModel *model in _selectedModelAray) {
        NSLog(@"打印选择的人的名字%@",model.name);
    }
    
    if ([self.delegate respondsToSelector:@selector(getSelectedStaff:)]) {
        [self.delegate getSelectedStaff:_selectedModelAray];
    }
    [self goToBack];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
      [_tableView reloadData];
    [_searchBar2 resignFirstResponder];
}
- (void)initTableView{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, vi2.maxY, _alphaView.width, _alphaView.height-64-TabbarH)];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_alphaView addSubview:_tableView];
    _tableView.hidden = NO;
    
    
//    UIView *tablevieHeader = [ViewTool getLineViewWith:CGRectMake(0, 0, _tableView.width, CellH) withBackgroudColor:[UIColor whiteColor]];
//    UIView *lien = [ViewTool getLineViewWith:CGRectMake(0, CellH -1, _alphaView.width, 1) withBackgroudColor:grayLineColor];
//    [tablevieHeader addSubview:lien];
//
//    UILabel *title = [ViewTool getLabelWith:CGRectMake(20, 0, 80.0f, CellH) WithTitle:@"全部" WithFontSize:16.0f WithTitleColor:blackFontColor WithTextAlignment:NSTextAlignmentLeft];
//    [tablevieHeader addSubview:title];
//    
//    UIButton *selec = [[UIButton alloc] initWithFrame:CGRectMake(_tableView.width - 50,CellH / 2.0f - 15 , 30, 30)];
//    [selec setBackgroundImage:[UIImage imageNamed:@"HY_list_btn_checkbox_normal"] forState:UIControlStateNormal];
//    selec.selected = NO;
//    [selec addTarget:self action:@selector(selectAll:) forControlEvents:UIControlEventTouchUpInside];
//    [tablevieHeader addSubview:selec];
//    
//    _tableView.tableHeaderView = tablevieHeader;
//    [_tableView registerClass:[HeaderView class] forCellReuseIdentifier:ReuseIdentifierHeader];
    _staffTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, vi2.maxY, _alphaView.width, _alphaView.height-64-TabbarH)];
    _staffTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _staffTableView.delegate = self;
    _staffTableView.dataSource = self;
    [_alphaView addSubview:_staffTableView];
    _staffTableView.hidden = YES;
//    _staffTableView.backgroundColor = NavBackColor;

    
    
}
#pragma mark --选择全部
//选择全部
//- (void)selectAll:(UIButton *)sender
//{
//    if (sender.selected == NO) {
//        [sender setBackgroundImage:[UIImage imageNamed:@"HY_list_btn_checkbox_selected"] forState:UIControlStateNormal];
//        if(_selectedNameArray.count != 0){
//        for (int i = 0; i<_allUsers.count; i++) {
//            UserModel *model = _allUsers[i];
//            if (![_selectedNameArray containsObject:model.name]) {
//                [_selectedNameArray addObject:model.name];
//                [_selectedModelAray addObject:model];
//            }
//        }
//        }else{
//            for (UserModel *mod  in _allUsers) {
//                [_selectedNameArray addObject:mod.name];
//                [_selectedModelAray addObject:mod];
//            }
//        }
//          [_tableView reloadData];
//    }else{
//         [sender setBackgroundImage:[UIImage imageNamed:@"HY_list_btn_checkbox_normal"] forState:UIControlStateNormal];
//        [_selectedNameArray removeAllObjects];
//        [_selectedModelAray removeAllObjects];
//          [_tableView reloadData];
//    }
//    sender.selected = !sender.selected;
//  
////    for (int i = 0; i<_allUsers.count; i++) {
////        UserModel *model = _allUsers[i];
////        if (![_selectedNameArray containsObject:model.name]) {
////            [_selectedNameArray addObject:model.name];
////            [_selectedModelAray addObject:model];
////        }
////    }
//}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [_searchArray removeAllObjects];
    if (searchBar.text.length == 0) {
        _tableView.hidden = NO;
        _staffTableView.hidden = YES;
        [_searchArray removeAllObjects];
        [_tableView reloadData];
    }
    if (searchBar.text.length != 0) {
        _tableView.hidden = YES;
        _staffTableView.hidden = NO;
        if (_expandArray.count != 0 ) {
       
        NSDictionary *dic = _expandArray[0];
        
        NSArray *allArr = dic[@"oneArray"];
        for (UserModel *model in allArr) {
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {//ios8出来的方法23432342
                
                if ([model.name.uppercaseString containsString:searchBar.text.uppercaseString]) {
                    [_searchArray addObject:model];
                }
                
            }else{
                
                NSRange range = [model.name.uppercaseString rangeOfString:searchBar.text.uppercaseString];
                if(range.length > 0)
                {
                    [_searchArray addObject:model];
                    
                }
            }
        }
        [_staffTableView reloadData];
        
    }
//    [searchBar resignFirstResponder];
        
    }
}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [_searchArray removeAllObjects];
     [searchBar resignFirstResponder];
    if (searchBar.text.length == 0) {
        _tableView.hidden = NO;
        _staffTableView.hidden = YES;
        [_searchArray removeAllObjects];
    }
    if (searchBar.text.length != 0) {
        _tableView.hidden = YES;
        _staffTableView.hidden = NO;
        if (_expandArray.count != 0) {
       
        NSDictionary *dic = _expandArray[0];
        NSArray *allArr = dic[@"oneArray"];
        for (UserModel *model in allArr) {
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {//ios8出来的方法
                
                if ([model.name.uppercaseString containsString:searchBar.text.uppercaseString]) {
                    [_searchArray addObject:model];
                }
                
            }else{
                
                NSRange range = [model.name.uppercaseString rangeOfString:searchBar.text.uppercaseString];
                if(range.length > 0)
                {
                    [_searchArray addObject:model];
                    
                }
            }
        }
        [_staffTableView reloadData];
    }
        
    }
}
#pragma mark --tableview  delegate
//- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
//{
//     [_searchArray removeAllObjects];
//    if (searchBar.text.length == 0) {
//        _tableView.hidden = NO;
//        _staffTableView.hidden = YES;
//        [_searchArray removeAllObjects];
//    }
//    if (searchBar.text.length != 0) {
//        _tableView.hidden = YES;
//        _staffTableView.hidden = NO;
//        NSDictionary *dic = _expandArray[0];
//        NSArray *allArr = dic[@"oneArray"];
//        for (UserModel *model in allArr) {
//            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {//ios8出来的方法
//                
//                if ([model.name.uppercaseString containsString:searchBar.text.uppercaseString]) {
//                    [_searchArray addObject:model];
//                }
//                
//            }else{
//                
//                NSRange range = [model.name.uppercaseString rangeOfString:searchBar.text.uppercaseString];
//                if(range.length > 0)
//                {
//                    [_searchArray addObject:model];
//                    
//                }
//            }
//        }
//        [_staffTableView reloadData];
//        [searchBar resignFirstResponder];
//    }
//}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSLog(@"section gehsu %ld",_expandArray.count);
    if (tableView == _tableView) {
           return _expandArray.count ;
    }else{
        return 1;
    }
 
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == _tableView) {
 
    if (section == 0) {
        hview2 = [[HeaderView2 alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 50.0f)];
        hview2.backgroundColor = [UIColor whiteColor];
        hview2.delegate = self;
        hview2.section = section;
        
        hview2.selec = [[UIButton alloc] initWithFrame:CGRectMake(KSCreenW - 50 - 50,CellH / 2.0f - 15 , 30, 30)];
        //    [_selec setBackgroundImage:[UIImage imageNamed:@"HY_list_btn_checkbox_normal"] forState:UIControlStateNormal];
        
        hview2.selec.selected = currentSelected;
        
        [hview2.selec addTarget:self action:@selector(selectAll:) forControlEvents:UIControlEventTouchUpInside];
        [hview2 addSubview:hview2.selec];
//        self.block = ^(BOOL isChoose){
//            hview2.selec.selected = isChoose;
//            if (hview2.selec.selected == YES) {
//                [hview2.selec setBackgroundImage:[UIImage imageNamed:@"HY_list_btn_checkbox_selected"] forState:UIControlStateNormal];
////                hview2.selec.selected = YES;
//            }else{
//                [hview2.selec setBackgroundImage:[UIImage imageNamed:@"HY_list_btn_checkbox_normal"] forState:UIControlStateNormal];
////                hview2.selec.selected = NO;
//            }
//        };
        if (hview2.selec.selected ==NO) {
            [hview2.selec setBackgroundImage:[UIImage imageNamed:@"HY_list_btn_checkbox_normal"] forState:UIControlStateNormal];
//            hview2.selec.selected = YES;
        }else{
            [hview2.selec setBackgroundImage:[UIImage imageNamed:@"HY_list_btn_checkbox_selected"] forState:UIControlStateNormal];
//            hview2.selec.selected = NO;
        }
        if (_expandArray.count != 0) {
            NSDictionary *dict = _expandArray[section];
            
            if ([dict[KISExpand] intValue] == 0) {
//                hview.arrowImage.image = [UIImage imageNamed:@"HY_list_icon_arrow_right.png"];
                hview2.coverBtn.selected = NO;
//                hview.chooseBtn.hidden = YES;
            }else{
//                hview.arrowImage.image = [UIImage imageNamed:@"HY_list_icon_arrow_down.png"];
                hview2.coverBtn.selected = YES;
//                hview.chooseBtn.hidden = NO;
            }
        return hview2;
    }
    }else{
//        NSLog(@"部门的个数%ld",_expandArray.count);
//    HeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:ReuseIdentifierHeader];
    HeaderView *hview = [[HeaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 50.0f)];
    hview.backgroundColor = [UIColor whiteColor];
    hview.delegate = self;

//    if (_expandArray.count != 0) {
        NSDictionary *dict = _expandArray[section];
        NSLog(@"dict%@",dict);
        DepartmentModel *model = dict[@"departModel"];
//        NSLog(@"部门de name %@",model.name);
        hview.section = section;
        NSString *key = model.name;
        hview.titleLabel.text = key;
        
        
        if ([dict[KISExpand] intValue] == 0) {
            hview.arrowImage.image = [UIImage imageNamed:@"HY_list_icon_arrow_right.png"];
            hview.coverBtn.selected = NO;
            hview.chooseBtn.hidden = YES;
        }else{
            hview.arrowImage.image = [UIImage imageNamed:@"HY_list_icon_arrow_down.png"];
            hview.coverBtn.selected = YES;
            hview.chooseBtn.hidden = NO;
        }
         return hview;
    }
  }
     return nil;
}
//点击全部的 全选
- (void)selectAll:(UIButton *)sender
{
    
    NSLog(@"sender.selected %d",sender.selected);
    if (sender.selected == NO) {
        [sender setBackgroundImage:[UIImage imageNamed:@"HY_list_btn_checkbox_selected"] forState:UIControlStateNormal];
        
        NSDictionary *dict = _expandArray[0];
        NSArray *ar = dict[@"oneArray"];
        
        if (_isCreatDepartment) {
            for (UserModel *model in ar) {
                
                if (model.departname && model.departname.length != 0 ) {
                    //如果 是添加部门的话，就不添加了
                }else{
                    
                    if(_selectedNameArray.count != 0 && _selectedModelAray.count != 0){
                        if (![_selectedNameArray containsObject:@(model.uid)]) {
                            [_selectedNameArray addObject:@(model.uid)];
                            [_selectedModelAray addObject:model];
                        }
                        //            for (int i= 0; i<_selectedNameArray.count; i++) {
                        //                NSString *nameStr = _selectedNameArray[i];
                        //                NSLog(@"全选的名字 --- 数组中已有名字,,%@ ---%@",model.name,nameStr);
                        //                if ([nameStr isEqualToString:model.name]) {
                        //                    [_selectedNameArray addObject:model.name];
                        //                    [_selectedModelAray addObject:model];
                        //                }
                        //            }
                    }else{
                        [_selectedNameArray addObject:@(model.uid)];
                        [_selectedModelAray addObject:model];
                    }
                    
                }
            }
            
        }else{
            for (UserModel *model in ar) {
                if(_selectedNameArray.count != 0 && _selectedModelAray.count != 0){
                    if (![_selectedNameArray containsObject:@(model.uid)]) {
                        [_selectedNameArray addObject:@(model.uid)];
                        [_selectedModelAray addObject:model];
                    }
                }else{
                    [_selectedNameArray addObject:@(model.uid)];
                    [_selectedModelAray addObject:model];
                }
            }
        }
    }else{
        [sender setBackgroundImage:[UIImage imageNamed:@"HY_list_btn_checkbox_normal"] forState:UIControlStateNormal];
        [_selectedNameArray removeAllObjects];
        [_selectedModelAray removeAllObjects];
    }
    currentSelected = !currentSelected;
    
    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    
}
//点击全部的 全选
//- (void)clickAllManWithIndexPath:(NSInteger)section WithIsChooseAllMan:(BOOL)isChooseAllMan
//{
//       NSLog(@"is choose %d",isChooseAllMan);
//    if (isChooseAllMan) {
//        NSArray *ar = _departManArray[section];
//        for (UserModel *model in ar) {
//            if(_selectedNameArray.count != 0 && _selectedModelAray.count != 0){
//                if (![_selectedNameArray containsObject:@(model.uid)]) {
//                    [_selectedNameArray addObject:@(model.uid)];
//                    [_selectedModelAray addObject:model];
//                }
//                //            for (int i= 0; i<_selectedNameArray.count; i++) {
//                //                NSString *nameStr = _selectedNameArray[i];
//                //                NSLog(@"全选的名字 --- 数组中已有名字,,%@ ---%@",model.name,nameStr);
//                //                if ([nameStr isEqualToString:model.name]) {
//                //                    [_selectedNameArray addObject:model.name];
//                //                    [_selectedModelAray addObject:model];
//                //                }
//                //            }
//            }else{
//                [_selectedNameArray addObject:@(model.uid)];
//                [_selectedModelAray addObject:model];
//            }
//        }
//    
////        [[NSUserDefaults standardUserDefaults] setObject:@(1) forKey:@"chooseAll"];
////        [[NSUserDefaults standardUserDefaults] synchronize];
//    }else{
//        [_selectedNameArray removeAllObjects];
//        [_selectedModelAray removeAllObjects];
//        
////        [[NSUserDefaults standardUserDefaults] setObject:@(2) forKey:@"chooseAll"];
////        [[NSUserDefaults standardUserDefaults] synchronize];
//    }
//    
//    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
//    
//    NSLog(@"ischoose %d",isChooseAllMan);
////        self.block(isChooseAllMan);
//}
//点击部门的 全选
- (void)clickSelectAllWithIndexPath:(NSInteger)indexPath_section
{
    isAllSelected = !isAllSelected;
    
    NSLog(@"点了哪一个 section --%ld",indexPath_section);
   
    NSDictionary *dict = _expandArray[indexPath_section];
    NSArray *ar = dict[@"oneArray"];
    
    if (isAllSelected == YES) {
        for (UserModel *model in ar) {
            if(_selectedNameArray.count != 0 && _selectedModelAray.count != 0){
                if (![_selectedNameArray containsObject:@(model.uid)]) {
                    [_selectedNameArray addObject:@(model.uid)];
                    [_selectedModelAray addObject:model];
                }
                //            for (int i= 0; i<_selectedNameArray.count; i++) {
                //                NSString *nameStr = _selectedNameArray[i];
                //                NSLog(@"全选的名字 --- 数组中已有名字,,%@ ---%@",model.name,nameStr);
                //                if ([nameStr isEqualToString:model.name]) {
                //                    [_selectedNameArray addObject:model.name];
                //                    [_selectedModelAray addObject:model];
                //                }
                //            }
            }else{
                [_selectedNameArray addObject:@(model.uid)];
                [_selectedModelAray addObject:model];
            }
        }
    }
    else{
        [_selectedNameArray removeAllObjects];
        [_selectedModelAray removeAllObjects];
    }
    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath_section] withRowAnimation:UITableViewRowAnimationAutomatic];
}
//点击全部的 伸展
- (void)clickAllWithIndexPath:(NSInteger)section withSendeSelectedWith:(BOOL)isSelectedAll
{
    if (isSelectedAll) {
        NSLog(@"展开");
        NSDictionary *dict = _expandArray[section];
        [dict setValue:@(1) forKey:KISExpand];
        [_tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
    }else{
        NSLog(@"收上");
        NSDictionary *dict = _expandArray[section];
        [dict setValue:@(0) forKey:KISExpand];
        [_tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}
//点击部门的 伸展
- (void)clickSectionWithIndexPath:(NSInteger)indexPath_section with:(BOOL)isExpand
{
    if (isExpand) {
        NSLog(@"展开");
         NSDictionary *dict = _expandArray[indexPath_section];
        [dict setValue:@(1) forKey:KISExpand];
        [_tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath_section] withRowAnimation:UITableViewRowAnimationNone];
    }else{
         NSLog(@"收上");
        NSDictionary *dict = _expandArray[indexPath_section];
        [dict setValue:@(0) forKey:KISExpand];
        [_tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath_section] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == _tableView) {
         return 50.0f;
    }else if(tableView == _staffTableView){
        return 0.0f;
    }
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    NSLog(@"部门的个数%ld",_expandArray.count);
    if (tableView == _tableView) {
   
    NSDictionary *dict = _expandArray[section];
    NSArray *oneArray = dict[@"oneArray"];
    int isExpand = [dict[KISExpand] intValue];
    if (isExpand == 0) {
        return 0;
    }else if(isExpand == 1){
//        NSArray *arr = _departManArray[section];
         NSLog(@"部门%ld,的个数%ld",section,oneArray.count);
        return oneArray.count;
    }
    }else if(tableView == _staffTableView){
         NSLog(@"搜索的个数%ld",_searchArray.count);
        return _searchArray.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_tableView == tableView) {
  
    NSLog(@"第几组 %ld",indexPath.section);
    NSDictionary *dict = _expandArray[indexPath.section];
    NSArray *arr = dict[@"oneArray"];
    
    UserModel *model = arr[indexPath.row];
     NSLog(@"某一个部门内人员的个数%ld",arr.count);
    ChooseDepartCell *cell = [ChooseDepartCell cellWithTableView:tableView];
    if ([_selectedNameArray containsObject:@(model.uid)]) {
        cell.selectedImage.image = [UIImage imageNamed:@"HY_list_btn_checkbox_selected"];
    }else{
       cell.selectedImage.image = [UIImage imageNamed:@"HY_list_btn_checkbox_normal"];
    }
    
    cell.model = model;
//    cell.cellWidth = _tableView.width;
    return cell;
    }else if(tableView == _staffTableView){
        UserModel *model = _searchArray[indexPath.row];
        NSLog(@"搜索的人员的个数%ld",_searchArray.count);
        ChooseDepartCell *cell2 = [ChooseDepartCell cellWithTableView:tableView];
        if ([_selectedNameArray containsObject:@(model.uid)]) {
            cell2.selectedImage.image = [UIImage imageNamed:@"HY_list_btn_checkbox_selected"];
        }else{
            cell2.selectedImage.image = [UIImage imageNamed:@"HY_list_btn_checkbox_normal"];
        }
        cell2.model = model;
        //    cell.cellWidth = _tableView.width;
        return cell2;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_tableView == tableView) {
   
      [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    NSLog(@"点击之前 名字数组有几个人%ld",_selectedModelAray.count);
    ChooseDepartCell *cell = [tableView cellForRowAtIndexPath:indexPath];
   
    NSDictionary *dict = _expandArray[indexPath.section];
    NSArray *departArr = dict[@"oneArray"];
    
    UserModel *model = departArr[indexPath.row];
    NSLog(@"点的的名字%@",model.name);
    if(self.isCreatDepartment){
        if (model.departname && model.departname.length != 0) {
            [self.view makeToast:@"改员工已加入其他部门"];
        }else{
            if ([_selectedNameArray containsObject:@(model.uid)]) {
                
                [_selectedNameArray removeObject:@(model.uid)];
                [_selectedModelAray removeObject:model];
                cell.selectedImage.image = [UIImage imageNamed:@"HY_list_btn_checkbox_normal"];
            }else{
                [_selectedNameArray addObject:@(model.uid)];
                [_selectedModelAray addObject:model];
                cell.selectedImage.image = [UIImage imageNamed:@"HY_list_btn_checkbox_selected"];
            }
        }
    }else {
    if ([_selectedNameArray containsObject:@(model.uid)]) {
        
        [_selectedNameArray removeObject:@(model.uid)];
        [_selectedModelAray removeObject:model];
         cell.selectedImage.image = [UIImage imageNamed:@"HY_list_btn_checkbox_normal"];
    }else{
        [_selectedNameArray addObject:@(model.uid)];
        [_selectedModelAray addObject:model];
         cell.selectedImage.image = [UIImage imageNamed:@"HY_list_btn_checkbox_selected"];
    }
    }
        
    }else if(tableView == _staffTableView){
         ChooseDepartCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UserModel *model = _searchArray[indexPath.row];
         NSLog(@"点击之前 名字数组有几个人%ld",_selectedModelAray.count);
        NSLog(@"点的是谁的名字%@",model.name);
        if(self.isCreatDepartment){
            if (model.departname && model.departname.length != 0) {
                [self.view makeToast:@"改员工已加入其他部门"];
            }else{
                if ([_selectedNameArray containsObject:@(model.uid)]) {
                    
                    [_selectedNameArray removeObject:@(model.uid)];
                    [_selectedModelAray removeObject:model];
                    cell.selectedImage.image = [UIImage imageNamed:@"HY_list_btn_checkbox_normal"];
                }else{
                    [_selectedNameArray addObject:@(model.uid)];
                    [_selectedModelAray addObject:model];
                    cell.selectedImage.image = [UIImage imageNamed:@"HY_list_btn_checkbox_selected"];
                }
            }
        }else{
            if ([_selectedNameArray containsObject:@(model.uid)]) {
                
                [_selectedNameArray removeObject:@(model.uid)];
                [_selectedModelAray removeObject:model];
                cell.selectedImage.image = [UIImage imageNamed:@"HY_list_btn_checkbox_normal"];
            }else{
                [_selectedNameArray addObject:@(model.uid)];
                [_selectedModelAray addObject:model];
                cell.selectedImage.image = [UIImage imageNamed:@"HY_list_btn_checkbox_selected"];
            }
        }
    }
//        NSLog(@"点击之hou 名字数组有几个人%ld",_selectedModelAray.count);
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [ChooseDepartCell cellHeight];
}
#pragma mark 加载数据 部门
-(void)initData{
//    [self.view makeToastActivity];
    NSDictionary * params2 = [NSDictionary dictionaryWithObjectsAndKeys:@(UID), @"uid", TOKEN, @"token", nil];
    AFHTTPRequestOperationManager * manager2 = [AFHTTPRequestOperationManager manager];
    manager2.requestSerializer.timeoutInterval = 30;
    [manager2 POST:GET_DEPARTMENT_URL parameters:params2 success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        [self.view hideToastActivity];
           [SVProgressHUD show];
        NSLog(@"GET_DEPARTMENT_URL:%@",responseObject);
        NSArray * userArray = [(NSDictionary *)responseObject objectForKey:@"data"];
        departMentCount = userArray.count;
        for (NSDictionary *dapart in userArray) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
           DepartmentModel * model = [[DepartmentModel alloc]init];
            [model setValuesForKeysWithDictionary:dapart];
            
            [dict setObject:model forKey:@"departModel"];
            [dict setObject:@(0) forKey:KISExpand];//开始都是不展开的
            [_expandArray addObject:dict];
            
//            [_departArray addObject:_model];
            //每个加载部门 数据234234srwerwerwerwedsfds
//            NSLog(@"即将加载下个部门的id是%ld",model.departId);
            if (_expandArray.count == userArray.count + 1) {
                for (int i = 0; i<userArray.count; i++) {
                    NSDictionary *dapart = userArray[i];
                    DepartmentModel * model = [[DepartmentModel alloc]init];
                    [model setValuesForKeysWithDictionary:dapart];
                    [self getDepartStaff:model];
                }
                

            }
                    }
        
//        [_tableView reloadData];
        if (userArray.count == 0) {
            NSLog(@"分组的个数%ld",_expandArray.count);
                      [SVProgressHUD dismiss];
             [self initTableView];
            [_tableView reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.view hideToastActivity];
        NSLog(@"%@",error);
    }];
}

//部门中的人员
- (void)getDepartStaff:(DepartmentModel *)depart{
    [_users removeAllObjects];
//    [self.view makeToastActivity];
       [SVProgressHUD show];
    NSDictionary * params2 = [NSDictionary dictionaryWithObjectsAndKeys:@(UID), @"uid", TOKEN, @"token", @(depart.departId), @"department", nil];
    
    NSLog(@"部门中人员数据的参数%@",params2);
    
    AFHTTPRequestOperationManager * manager2 = [AFHTTPRequestOperationManager manager];
    manager2.requestSerializer.timeoutInterval = 20;
    [manager2 POST:GET_USER_BY_DEPARTMENT_URL parameters:params2 success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"部门中人员数据的:%@",responseObject);
        NSArray * departArray = [(NSDictionary *)responseObject objectForKey:@"data"];
        NSMutableArray *oneArray =[NSMutableArray array];
        
        NSLog(@"部门id %d对应的部门人数%ld",depart.departId,departArray.count);
        for (NSDictionary *user  in departArray) {
         UserModel * userModel = [[UserModel alloc]init];
            [userModel setValuesForKeysWithDictionary:user];
//            [_allUsers addObject:userModel];//把所有的 部门中的人 都添加进来
            [oneArray addObject:userModel];
        }
//        for (int i = 0; i< _expandArray.count; i++) {
//            if (i != 0) {
//                NSDictionary *dict = _expandArray[i];
//                
//                if ([dict[@"departModel"] departId] == depart.departId) {
//                    [_departManArray insertObject:oneArray atIndex:i];
//                }
//            }
//          3453454sdfjke2
//        }
        for (int i =0 ; i<_expandArray.count; i++) {
            if (i != 0) {
                NSMutableDictionary * dict = _expandArray[i];
                DepartmentModel *model = dict[@"departModel"];
                if (model.departId == depart.departId) {
                    [dict setObject:oneArray forKey:@"oneArray"];
                }
            }
        }
        [_departManArray addObject:oneArray];
//        [_departManArray insertObject:oneArray atIndex:i];
        
//        [_staffTableView reloadData];
        if (_departManArray.count == departMentCount + 1) {
            
            for (int i =0 ; i<_departManArray.count; i++) {
//                NSLog(@"%@")
//                DepartmentModel *deptmodel =_expandArray[i];
//                NSLog(@"%@",deptmodel.name);
//                for (UserModel * userModel in _departManArray[i]) {
//                    NSLog(@"打印第 %d个部门中的人 %d -- %@",i,userModel.uid,userModel.name);
//                }
            }
             [SVProgressHUD dismiss];
            [self initTableView];
       
            
             [_tableView reloadData];
        }
        
          [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.view hideToastActivity];
        NSLog(@"%@",error);
    }];
}
//GET_USER_BY_DEPARTMENT_URL 所有的人员
- (void)addAllUsers{
    
//    if (_allUsers.count == 0) {
       [SVProgressHUD show];
        NSDictionary * dic =@{@"token":TOKEN,@"uid":@(UID)};
    NSLog(@"dic%@",dic);
    
    [DataTool postWithUrl:BUSINESS_ADDRESS_BOOK_URL parameters:dic success:^(id data) {
            [self.view hideToastActivity];
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"所有员工的数量%@",jsonDic);
            NSMutableArray *array = jsonDic[@"data"];
     
            for (int i =0; i<array.count; i++) {
                //
                UserModel *userModel = [[UserModel alloc]init];
                id dd = [DataTool changeType:array[i]];
                [userModel setValuesForKeysWithDictionary:dd];
                [_allUsers addObject:userModel];
            }
             [SVProgressHUD dismiss];
            if (_allUsers.count == array.count) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setObject:@(0) forKey:KISExpand];
                [dict setObject:_allUsers forKey:@"oneArray"];
                [_expandArray addObject:dict];
                
                [_departManArray addObject:_allUsers];
//                   [SVProgressHUD dismiss];
                 [self initData];//部门数据
            }
//            [_departManArray addObject:array];
             [SVProgressHUD dismiss];
//            [_staffTableView reloadData];
        } fail:^(NSError *error) {
            [self.view hideToastActivity];
            NSLog(@"%@",error);
        }];
//    }
}

#pragma mark 添加搜索栏
-(void)addSearchBar{
    //    CGRect searchBarRect=CGRectMake(0, 0, _alphaView.width, 44);
//    UIView *vi1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _alphaView.width, 44)];
//    vi1.backgroundColor  = graySectionColor;
    //    [self.view addSubview:vi1];
    
//    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, vi1.width , 44)];
//    [_searchBar setBackgroundImage:[ViewTool getImageFromColor:graySectionColor WithRect:_searchBar.frame]];
//    //    _searchBar.showsCancelButton = YES;
//    _searchBar.placeholder =@"搜索";
//    [vi1 addSubview:_searchBar];
//    //    for (UIView *view in [_searchBar.subviews[0] subviews]) {
//    //        if ([view isKindOfClass:[UIButton class]]) {
//    //            UIButton *btn = (UIButton *)view;
//    //            [btn setTitle:@"取消" forState:UIControlStateNormal];
//    //            [btn setTitleColor:grayFontColor forState:UIControlStateNormal];
//    //            btn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
//    //        }
//    //    }
//    _searchBar.delegate = self;
//    
//    //    _searchBar=[[UISearchBar alloc]initWithFrame:searchBarRect];
//    //    _searchBar.placeholder=@"搜索";
//    //    _searchBar.showsCancelButton=YES;//显示取消按钮
//    //添加搜索框到页眉位置
//    //    _searchBar.delegate=self;
//    
//    self.tableView.tableHeaderView = vi1;
//    //    CGRect searchBarRect2=CGRectMake(0, 0, _alphaView.width, 44);
    vi2 = [[UIView alloc]initWithFrame:CGRectMake(0, 64, _alphaView.width, 44)];
    vi2.backgroundColor  = UIColorFromRGB(0xe8ecef);
    [_alphaView addSubview:vi2];
    
    _searchBar2 = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, vi2.width , 44)];
    //[UIColor colorWithRed:226.0f / 255.0f green:231.0f / 255.0f  blue:234.0f / 255.0f  alpha:1]
    [_searchBar2 setBackgroundImage:[ViewTool getImageFromColor:UIColorFromRGB(0xe8ecef) WithRect:_searchBar.frame]];
    //    _searchBar.showsCancelButton = YES;
    _searchBar2.placeholder =@"搜索";
    [vi2 addSubview:_searchBar2];
    //    for (UIView *view in [_searchBar.subviews[0] subviews]) {
    //        if ([view isKindOfClass:[UIButton class]]) {
    //            UIButton *btn = (UIButton *)view;
    //            [btn setTitle:@"取消" forState:UIControlStateNormal];
    //            [btn setTitleColor:grayFontColor forState:UIControlStateNormal];
    //            btn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    //        }
    //    }
    _searchBar2.delegate = self;
    
    //    _searchBar2=[[UISearchBar alloc]initWithFrame:searchBarRect2];
    //    _searchBar2.placeholder=@"搜索";
    //    _searchBar2.showsCancelButton=YES;//显示取消按钮
    //添加搜索框到页眉位置
    //    _searchBar2.delegate=self;
    
//    self.tableView.tableHeaderView = vi2;
}

//- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
//    [searchBar resignFirstResponder];
//    isSearch = NO;
//    [_searchArray removeAllObjects];
//    [_clientTableView reloadData];
//    
//    
//}
//- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
//{
//    
//    
//    //    NSArray * companyArray = [_customerList objectForKey:@"company"];
//    
//    
//}
//- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
//{
//    [_backView removeFromSuperview];
//    
//    [_searchArray removeAllObjects];
//    if(searchText != nil){
//        isSearch = YES;
//    }
//    for (int i = 0; i < _companyList.count; i++) {
//        //        NSLog(@"%@",_companyList[i]);
//        NSString *companyStr = _companyList[i];
//        NSRange rang = [companyStr rangeOfString:searchText];
//        if (rang.length != 0) {
//            [_searchArray addObject:_companyList[i]];
//            [_clientTableView reloadData];
//        }
//    }
//    if ([searchText isEqualToString: @""]) {
//        [_searchArray removeAllObjects];
//        isSearch = NO;
//        [_clientTableView reloadData];
//        _backView = [[UIView alloc] initWithFrame:CGRectMake(0, searchBar.maxY + 64, KSCreenW, KSCreenH - searchBar.maxY - 64)];
//        _backView.backgroundColor = [UIColor clearColor];
//        [self.view addSubview:_backView];
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
//        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
//        [_backView addGestureRecognizer:tap];
//        [_backView addGestureRecognizer:pan];
//    }
//}
//- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
//{
//    [_searchArray removeAllObjects];
//    isSearch = YES;
//    //    NSArray * companyArray = [_customerList objectForKey:@"company"];
//    for (int i = 0; i < _companyList.count; i++) {
//        NSLog(@"%@",_companyList[i]);
//        NSString *companyStr = _companyList[i];
//        NSRange rang = [companyStr rangeOfString:searchBar.text];
//        if (rang.length != 0) {
//            [_searchArray addObject:_companyList[i]];
//            [_clientTableView reloadData];
//        }
//    }
//    [_searchBar resignFirstResponder];
//}



- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    [_expandArray removeAllObjects];
    [_departManArray removeAllObjects];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.hidesBottomBarWhenPushed = NO;
}

-(void)resetView:(UIButton *)btn{
//    [_expandArray removeAllObjects];
//    [_departManArray removeAllObjects];
    [_selectedModelAray removeAllObjects];
    [_selectedNameArray removeAllObjects];
//     [hview2.selec setBackgroundImage:[UIImage imageNamed:@"HY_list_btn_checkbox_normal"] forState:UIControlStateNormal];
//    NSLog(@"全部的全选按钮 选中状态%d",hview2.selec.selected);
//    hview2.selec.selected = NO;
    currentSelected = NO;
//    [self addAllUsers];
//    [_selectedDeparts removeAllObjects];
//    [_selectedUsers removeAllObjects];
    [_tableView reloadData];
    [_staffTableView reloadData];
}
-(void)closeSelectView{
//    [_searchBar resignFirstResponder]; //退出键盘
    [_searchBar2 resignFirstResponder];
//    if (self.tableView.hidden) {
//        self.tableView.hidden = NO;
//        self.staffTableView.hidden = YES;
//        [_users removeAllObjects];
//        [self.staffTableView reloadData];
//    }else{
        [self goToBack];
//    }
}
- (void)goToBack{
    [_selectedNameArray removeAllObjects];
    [_selectedModelAray removeAllObjects];
    //    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
